﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ELS_Proj.User
{
    public partial class GroupPermissionManagementForm : MdiChildForm
    {
        PermissionController permissionController = new PermissionController();
        GroupController groupController = new GroupController();
        GrantController grantController = new GrantController();

        bool isLoadedData = false;
        Dictionary<String, int> permissionOfGroups;
        Dictionary<String, int> allPermission;
        public GroupPermissionManagementForm()
        {
            InitializeComponent();            
        }

        private bool LoadChkPer_GrpPer()
        {
            txtPermissionName.BackColor = Color.WhiteSmoke;
            txtPermissionDesc.BackColor = Color.WhiteSmoke;
            pnlGrp.Enabled = true;
            pnlPer.Enabled = true;

            DataTable dtPermission = new DataTable();
            dtPermission = permissionController.GetAllPermission();
            ((ListBox)chkbPer_GrpPer).DataSource = dtPermission;
            ((ListBox)chkbPer_GrpPer).DisplayMember = "CODE";
            ((ListBox)chkbPer_GrpPer).ValueMember = "ID";

            if (dtPermission.Rows.Count > 0)
            {
                return true;
            }
            else return false;
        }

        private bool LoadChkGroup_GrpPer()
        {
            txtGroupName.BackColor = Color.WhiteSmoke;
            txtGroupDescription.BackColor = Color.WhiteSmoke;
            pnlGrp.Enabled = true;
            pnlPer.Enabled = true;

            DataTable dtGrp = new DataTable();
            dtGrp = groupController.GetAllGroups();
            ((ListBox)chkbGrp_GrpPer).DataSource = dtGrp;
            ((ListBox)chkbGrp_GrpPer).DisplayMember = "GROUPNAME";
            ((ListBox)chkbGrp_GrpPer).ValueMember = "GROUP_ID";

            if (dtGrp.Rows.Count > 0)
            {
                return true;
            }
            else return false;
        }
        private bool LoadListGroups()
        {
            DataTable dtGroups = new DataTable();
            dtGroups = groupController.GetAllGroups();
            lbGroups.DataSource = dtGroups;
            lbGroups.DisplayMember = "GROUPNAME";
            lbGroups.ValueMember = "GROUP_ID";

            if (dtGroups.Rows.Count > 0)
            {
                return true;
            }
            else return false;
        }

        private bool LoadListPermission()
        {
            DataTable dtPermission = new DataTable();
            dtPermission = permissionController.GetAllPermission();
            ((ListBox)chkbPermission).DataSource = dtPermission;
            ((ListBox)chkbPermission).DisplayMember = "CODE";
            ((ListBox)chkbPermission).ValueMember = "ID";

            if (dtPermission.Rows.Count > 0)
            {
                return true;
            }
            else return false;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            string currentGroupId = lbGroups.SelectedValue.ToString();
            List<int> newPermissions = new List<int>();
            foreach (object itemChecked in chkbPermission.CheckedItems)
            {
                DataRowView castedItem = itemChecked as DataRowView;
                string comapnyName = castedItem["CODE"].ToString();
                int id = int.Parse(castedItem["ID"].ToString());
                newPermissions.Add(id);
            }

            grantController.UpdatePermissionOfGroup(currentGroupId, newPermissions);

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.GroupPermissionManagementForm_Load(sender, e);
        }

        private void lbGroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            int groupId = 0;
            if (isLoadedData)
            {

                groupId = int.Parse(lbGroups.SelectedValue.ToString());
                
                for (int j = 0; j < chkbPermission.Items.Count; j++)
                {
                    chkbPermission.SetItemChecked(j, false);

                    allPermission = permissionController.GetAllPermissionByDictionary();
                    permissionOfGroups = permissionController.GetPermissionByGroupId(groupId);

                    int i = 0;
                    foreach (KeyValuePair<string, int> pairAll in allPermission)
                    {
                        foreach (KeyValuePair<string, int> pairUser in permissionOfGroups)
                        {
                            if (pairAll.Value == pairUser.Value)
                            {
                                chkbPermission.SetItemChecked(i, true);
                            }
                        }
                        i++;
                    }
                }
            }
        }

        private void chkbPermission_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoadedData)
            {
                int permissionId = 0;
                permissionId = int.Parse(chkbPermission.SelectedValue.ToString());
            }
        }
        //string currentGroupName = "";
        private void chkbGrp_GrpPer_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (isLoadedData)
            {
                string currentGroupName = chkbGrp_GrpPer.GetItemText(chkbGrp_GrpPer.Items[e.Index]);
                DataTable groupInfo = groupController.SelectGroupByName(currentGroupName);
                txtGroupName.Text = groupInfo.Rows[0]["GROUPNAME"].ToString();
                txtGroupDescription.Text = groupInfo.Rows[0]["DESCRIPTION"].ToString();
            }
        }
        //string currentPermissionCode = "";
        private void chkbPer_GrpPer_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (isLoadedData)
            {
                string currentPermissionCode = chkbPer_GrpPer.GetItemText(chkbPer_GrpPer.Items[e.Index]);
                DataTable groupInfo = permissionController.SelectPermissionByCode(currentPermissionCode);
                txtPermissionName.Text = groupInfo.Rows[0]["PER_CD"].ToString();
                txtPermissionDesc.Text = groupInfo.Rows[0]["PER_DESC"].ToString();
            }
        }

        bool isAddNewGrp = false;
        bool isEditGrp = false;
        bool isDeleteGrp = false;
        private void btnEditGrp_Click(object sender, EventArgs e)
        {
            List<int> listSelectedGroup = GetListGroupSelect();
            bool isHavingSelect = listSelectedGroup.Count > 0;
            bool isEditable = listSelectedGroup.Count == 1;
            if (isHavingSelect)
            {
                if (isEditable)
                {
                    pnlGrp.Enabled = true;
                    pnlPer.Enabled = false;
                    txtGroupName.BackColor = Color.White;
                    txtGroupDescription.BackColor = Color.White;

                    DataTable groupInfo = groupController.SelectGroupById(listSelectedGroup[0]);
                    txtGroupName.Text = groupInfo.Rows[0]["GROUPNAME"].ToString();
                    txtGroupDescription.Text = groupInfo.Rows[0]["DESCRIPTION"].ToString();

                    chkbGrp_GrpPer.Enabled = false;
                    txtGroupName.ReadOnly = false;
                    txtGroupDescription.ReadOnly = false;

                    btnAddGrp.Visible = false;
                    btnEditGrp.Visible = false;
                    btnDeleteGrp.Visible = false;

                    btnSaveGrp.Visible = true;
                    btnCancelGrp.Visible = true;

                    isAddNewGrp = false;
                    isEditGrp = true;
                    isDeleteGrp = false;

                    txtGroupName.Focus();
                }
                else
                {
                    UserCommon.NotifyOnMainForm(this, UserCommon.SelectUpdateGroup_NotMulti, 0);
                }
            }
            else
            {
                UserCommon.NotifyOnMainForm(this, UserCommon.SelectUpdateGroup_DoNotSelect, 0);
            }
        }

        private void btnSaveGrp_Click(object sender, EventArgs e)
        {
            string grpName = txtGroupName.Text.Trim();
            string grpDes = txtGroupDescription.Text.Trim();
            int currentSelectGroupId = GetListGroupSelect()[0];

            if (grpName.Length > 0)
            {
                txtGroupName.ReadOnly = false;
                txtGroupDescription.ReadOnly = false;
                if (isEditGrp)
                {
                    bool isUpdateGroupSuccess = groupController.UpdateGroup(currentSelectGroupId, grpName, grpDes);
                    if (isUpdateGroupSuccess)
                    {
                        LoadChkGroup_GrpPer();
                        RefreshGroup();
                    }
                    else
                    {
                        UserCommon.NotifyOnMainForm(this, UserCommon.UpdateGroup_Fail, -1);
                    }
                }
                if (isAddNewGrp)
                {
                    bool isAddNewGroupSuccess = groupController.AddNewGroup(grpName, grpDes);
                    if (isAddNewGroupSuccess)
                    {
                        LoadChkGroup_GrpPer();
                        RefreshGroup();
                    }
                }
            }

        }

        private void RefreshGroup()
        {
            chkbGrp_GrpPer.Enabled = true;
            txtGroupName.Text = "";
            txtGroupDescription.Text = "";
            txtGroupName.BackColor = Color.WhiteSmoke;
            txtGroupDescription.BackColor = Color.WhiteSmoke;

            txtGroupName.ReadOnly = true;
            txtGroupDescription.ReadOnly = true;

            btnAddGrp.Visible = true;
            btnEditGrp.Visible = true;
            btnDeleteGrp.Visible = true;

            btnSaveGrp.Visible = false;
            btnCancelGrp.Visible = false;

            isAddNewGrp = false;
            isEditGrp = false;
            isDeleteGrp = false;

            pnlGrp.Enabled = true;
            pnlPer.Enabled = true;
        }

        private void btnCancelGrp_Click(object sender, EventArgs e)
        {
            RefreshGroup();
        }

        private void btnCancelPer_Click(object sender, EventArgs e)
        {
            RefreshPermission();
        }

        private void RefreshPermission()
        {
            chkbPer_GrpPer.Enabled = true;
            txtPermissionName.Text = "";
            txtPermissionDesc.Text = "";
            txtPermissionName.BackColor = Color.WhiteSmoke;
            txtPermissionDesc.BackColor = Color.WhiteSmoke;

            txtPermissionName.ReadOnly = true;
            txtPermissionDesc.ReadOnly = true;

            btnAddPer.Visible = true;
            btnEditPer.Visible = true;
            btnDeletePer.Visible = true;

            btnSavePer.Visible = false;
            btnCancelPer.Visible = false;

            isAddNewPer = false;
            isEditPer = false;
            isDeletePer = false;

            pnlGrp.Enabled = true;
            pnlPer.Enabled = true;
        }

        private void btnSavePer_Click(object sender, EventArgs e)
        {
            string perCode = txtPermissionName.Text.Trim();
            string perDes = txtPermissionDesc.Text.Trim();
            int currentSelectPermissionId = GetListPermissionSelect()[0];
            if (perCode.Length > 0)
            {
                txtPermissionName.ReadOnly = false;
                txtPermissionDesc.ReadOnly = false;
                if (isEditPer)
                {
                    permissionController.UpdatePermission(currentSelectPermissionId, perCode, perDes);
                    LoadChkPer_GrpPer();
                    RefreshPermission();
                }
                if(isAddNewPer)
                {
                    permissionController.AddNewPermission(perCode, perDes);
                    LoadChkPer_GrpPer();
                    RefreshPermission();
                }
            }
        }
        bool isAddNewPer = false;
        bool isEditPer = false;
        bool isDeletePer = false;
        private void btnEditPer_Click(object sender, EventArgs e)
        {
            List<int> listSelectedPermission = GetListPermissionSelect();
            bool isHavingSelect = listSelectedPermission.Count > 0;
            bool isEditable = listSelectedPermission.Count == 1;
            if (isHavingSelect)
            {
                if (isEditable)
                {
                    pnlGrp.Enabled = false;
                    pnlPer.Enabled = true;
                    chkbPer_GrpPer.Enabled = false;

                    DataTable permissionInfo = permissionController.SelectPermissionById(listSelectedPermission[0]);
                    txtPermissionName.Text = permissionInfo.Rows[0]["PER_CD"].ToString();
                    txtPermissionDesc.Text = permissionInfo.Rows[0]["PER_DESC"].ToString();

                    txtPermissionName.BackColor = Color.White;
                    txtPermissionDesc.BackColor = Color.White;
                    txtPermissionName.ReadOnly = false;
                    txtPermissionDesc.ReadOnly = false;

                    btnAddPer.Visible = false;
                    btnEditPer.Visible = false;
                    btnDeletePer.Visible = false;

                    btnSavePer.Visible = true;
                    btnCancelPer.Visible = true;

                    isAddNewPer = false;
                    isEditPer = true;
                    isDeletePer = false;

                    txtPermissionName.Focus();
                }
                else
                {
                    UserCommon.NotifyOnMainForm(this, UserCommon.SelectUpdatePermission_NotMulti, 0);
                }
            }
            else 
            {
                UserCommon.NotifyOnMainForm(this, UserCommon.SelectUpdatePermission_DoNotSelect, 0);
            }
        }

        private void btnAddGrp_Click(object sender, EventArgs e)
        {
            chkbGrp_GrpPer.Enabled = false;
            txtGroupName.Text = "";
            txtGroupDescription.Text = "";
            txtGroupName.BackColor = Color.White;
            txtGroupDescription.BackColor = Color.White;
            pnlGrp.Enabled = true;
            pnlPer.Enabled = false;

            txtGroupName.ReadOnly = false;
            txtGroupDescription.ReadOnly = false;

            btnAddGrp.Visible = false;
            btnEditGrp.Visible = false;
            btnDeleteGrp.Visible = false;

            btnSaveGrp.Visible = true;
            btnCancelGrp.Visible = true;

            isAddNewGrp = true;
            isEditGrp = false;
            isDeleteGrp = false;

            txtGroupName.Focus();
        }

        private void btnAddPer_Click(object sender, EventArgs e)
        {
            chkbPer_GrpPer.Enabled = false;
            txtPermissionName.BackColor = Color.White;
            txtPermissionDesc.BackColor = Color.White;
            pnlGrp.Enabled = false;
            pnlPer.Enabled = true;
            txtPermissionName.Text = "";
            txtPermissionDesc.Text = "";
            txtPermissionName.ReadOnly = false;
            txtPermissionDesc.ReadOnly = false;

            btnAddPer.Visible = false;
            btnEditPer.Visible = false;
            btnDeletePer.Visible = false;

            btnSavePer.Visible = true;
            btnCancelPer.Visible = true;

            isAddNewPer = true;
            isEditPer = false;
            isDeletePer = false;

            txtPermissionName.Focus();
        }

        private void btnDeleteGrp_Click(object sender, EventArgs e)
        {
            isDeleteGrp = true;
            isAddNewGrp = false;
            isEditGrp = true;

            pnlGrp.Enabled = true;
            pnlPer.Enabled = true;

            List<int> listSelectedGroup = GetListGroupSelect();
            bool isHavingSelect = listSelectedGroup.Count >0;
            if (isHavingSelect)
            {
                DialogResult dialogConfirm = MessageBox.Show(UserCommon.DeleteGroup_Message, UserCommon.DeleteGroup_MessageBox_Title, MessageBoxButtons.YesNo);
                if (dialogConfirm == DialogResult.Yes)
                {
                    bool isDeleteSuccess = groupController.DeleteSelectGroup(listSelectedGroup);
                    if (isDeleteSuccess)
                    {
                        UserCommon.NotifyOnMainForm(this, UserCommon.DeleteGroup_Success, 1);
                        LoadChkGroup_GrpPer();
                        RefreshGroup();
                    }
                    else
                    {
                        UserCommon.NotifyOnMainForm(this, UserCommon.DeleteGroup_Fail, -1);
                    }
                }
                else if (dialogConfirm == DialogResult.No)
                {
                    return;
                }
            }
            else
            {
                UserCommon.NotifyOnMainForm(this, UserCommon.DeleteGroup_DoNotSelect, 0);
            }
        }

        private List<int> GetListGroupSelect()
        {
            List<int> listGroupIdSelect = new List<int>();
            foreach (object itemChecked in chkbGrp_GrpPer.CheckedItems)
            {
                DataRowView castedItem = itemChecked as DataRowView;                
                int id = int.Parse(castedItem["GROUP_ID"].ToString());
                listGroupIdSelect.Add(id);
            }
            return listGroupIdSelect;
        }

        private List<int> GetListPermissionSelect()
        {
            List<int> listSelectPermissionIdSelect = new List<int>();
            foreach (object itemChecked in chkbPer_GrpPer.CheckedItems)
            {
                DataRowView castedItem = itemChecked as DataRowView;
                int id = int.Parse(castedItem["ID"].ToString());
                listSelectPermissionIdSelect.Add(id);
            }
            return listSelectPermissionIdSelect;
        }

        private void btnDeletePer_Click(object sender, EventArgs e)
        {
            isDeletePer = true;
            isAddNewPer = false;
            isEditGrp = true;

            pnlPer.Enabled = true;
            pnlGrp.Enabled = true;

            List<int> listSelectedPermission = GetListPermissionSelect();
            bool isHavingSelect = listSelectedPermission.Count > 0;
            if (isHavingSelect)
            {
                DialogResult dialogConfirm = MessageBox.Show(UserCommon.DeletePermission_Message, UserCommon.DeletePermission_MessageBox_Title, MessageBoxButtons.YesNo);
                if (dialogConfirm == DialogResult.Yes)
                {
                    bool isDeleteSuccess = permissionController.DeleteSelectPermission(listSelectedPermission);
                    if (isDeleteSuccess)
                    {
                        UserCommon.NotifyOnMainForm(this, UserCommon.DeletePermission_Success, 1);
                        LoadChkPer_GrpPer();
                        RefreshPermission();
                    }
                    else
                    {
                        UserCommon.NotifyOnMainForm(this, UserCommon.DeletePermission_Fail, -1);
                    }
                }
                else if (dialogConfirm == DialogResult.No)
                {
                    return;
                }
            }
            else
            {
                UserCommon.NotifyOnMainForm(this, UserCommon.DeletePermission_DoNotSelect, 0);
            }
        }

        private void tabControl1_Click(object sender, EventArgs e)
        {
            this.GroupPermissionManagementForm_Load(sender, e);
        }

        private void GroupPermissionManagementForm_Load(object sender, EventArgs e)
        {
            isLoadedData = LoadListGroups() && LoadListPermission() && LoadChkGroup_GrpPer() && LoadChkPer_GrpPer();
        }            
    }
}
